<script setup lang="ts">
import { inject, ref, onMounted, onUnmounted, watch } from 'vue'
import { onClickOutside } from '@vueuse/core'
import { dropdownSymbol } from './dropdownContext'


const dropdownContext = inject(dropdownSymbol)

const refTrigger = ref<HTMLElement>()

const isClickTrigger = dropdownContext?.triggerType === 'click'

onClickOutside(refTrigger, () => {
  // refTrigger 有问题
  console.log(refTrigger.value)
  dropdownContext?.close()
})

const calculatePosition = (placement = 'left', trigger: HTMLElement) => {
  const { top, left, height } = trigger.getBoundingClientRect()
  let topPosition = top + height
  let leftPosition = 0

  switch (placement) {
    case 'left':
      leftPosition = left
      break
    case 'center':
      leftPosition = left - trigger.offsetWidth / 2
      break
    default:
      // Handle other cases if necessary
      break
  }

  return { topPosition, leftPosition }
}

const setPosition = () => {
  if (!refTrigger.value) return
  const { topPosition, leftPosition } = calculatePosition(dropdownContext?.menuPlacement, refTrigger.value)
  dropdownContext?.setPosition(topPosition, leftPosition)
}

const trigger = () => {
  setPosition()
  dropdownContext?.open()
}

const pageScrollEvent = () => dropdownContext?.visible && dropdownContext.close()

const bindTriggerEvent = () => {
  isClickTrigger && refTrigger.value?.addEventListener('click', trigger)
  document.addEventListener('scroll', pageScrollEvent)
}

const unbindTriggerEvent = () => {
  isClickTrigger && refTrigger.value?.removeEventListener('click', trigger)
  document.removeEventListener('scroll', pageScrollEvent)
}

onMounted(() => {

  bindTriggerEvent()

  if (dropdownContext?.triggerType === 'click') return

  watch(() => dropdownContext?.isHovered?.value, (val) => {
    val ? trigger() : dropdownContext?.close()
  })

})

onUnmounted(() => {
  unbindTriggerEvent()
})

</script>

<template>
  <div class="kx-dropdown-trigger" ref="refTrigger">
    <slot></slot>
  </div>
</template>
